#include "trng_bsp.h"
#include "main.h"

static ErrStatus trng_ready_check(void)
{
    uint32_t timeout = 0;
    FlagStatus trng_flag = RESET;
    ErrStatus reval = SUCCESS;

    /* check wherther the random data is valid */
    do
    {
        timeout++;
        trng_flag = trng_flag_get(TRNG_FLAG_DRDY);
    } while ((RESET == trng_flag) && (0xFF > timeout));

    if (RESET == trng_flag)
    {
        /* ready check timeout */
        trng_flag = trng_flag_get(TRNG_FLAG_CECS);
        trng_flag = trng_flag_get(TRNG_FLAG_SECS);
        reval = ERROR;
    }

    /* return check status */
    return reval;
}

uint32_t randomNumGet(void)
{
    /*enable TRNG module clock */
    rcu_osci_on(RCU_IRC48M);
    if (ERROR == rcu_osci_stab_wait(RCU_IRC48M))
    {
        LOG_E("IRC48M oscillator stabilization timeout");
    }
    rcu_periph_clock_enable(RCU_TRNG);
    trng_enable();

    uint32_t random_data = 0;
    if (SUCCESS == trng_ready_check())
        random_data = trng_get_true_random_data();
    
    /* disable TRNG module clock */
    rcu_periph_clock_disable(RCU_TRNG);
    rcu_osci_off(RCU_IRC48M);

    return random_data;
}